//
//  UIControl+Extension.swift
//  YangFoundation
//
//  Created by yuyang on 2021/12/21.
//

import Foundation

/// 扩大响应热区
extension UIControl {
    // 记录运行时的 key
    struct ButtonRuntimeKey {
        static let expandTouchRangeKey = UnsafeRawPointer.init(bitPattern: "ExpandTouchRange".hashValue)
    }
    
    /// 设置扩大热区的范围
    public var hitTestEdgeInsets: UIEdgeInsets? {
        set {
            objc_setAssociatedObject(self, ButtonRuntimeKey.expandTouchRangeKey!, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        }
        get {
            return (objc_getAssociatedObject(self, ButtonRuntimeKey.expandTouchRangeKey!) as? UIEdgeInsets) ?? UIEdgeInsets.zero
        }
    }
    
    /// 重写点是否包含在 view 的区域内
    open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        if hitTestEdgeInsets == UIEdgeInsets.zero || !isEnabled || isHidden {
            return super.point(inside: point, with: event)
        }
        let relativeFrame = bounds
        let hitFrame = relativeFrame.inset(by: hitTestEdgeInsets!)
        
        return hitFrame.contains(point)
    }
}
